package com.tushu.dao;


import com.tushu.model.Book;
import com.tushu.utils.TimeTools;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class BookDao extends BaseDAO{
    public int addBook(Book book) {
        String sql = "insert into tb_book values(null,?,?,?,?,?)";
        return super.update(sql, new Object[]{book.getIsbn(), book.getBookName()
                , book.getAuthor(), book.getPublisher(), book.getNum()});
    }

    public int updateBook(Book book) {
        String sql = "update tb_book set isbn=?,book_name=?,author=?,publisher=?,num=? where id=?";
        return super.update(sql, new Object[]{book.getIsbn(), book.getBookName(), book.getAuthor(),
                book.getPublisher(), book.getNum()
                , book.getId()});
    }

    public int deleteBook(String isbn) {
        String sql = "delete from tb_book where isbn=?";
        return super.update(sql, new Object[]{isbn});
    }

    public List<Book> getBookList() {
        String sql = "select * from tb_book";
        return super.selectAll(sql, new Object[]{});
    }

    public Book getBookByName(String name) {
        String sql = "select * from tb_book where book_name=?";
        return super.select(sql, new Object[]{name});
    }

    public Book getBookByIsbn(String isbn) {
        String sql = "select * from tb_book where isbn=?";
        return super.select(sql, new Object[]{isbn});
    }

    //添加借书记录
    public int addRecord(int stuId,int bookId){
        String sql = "insert into tb_lend values(null,?,?,?,?)";
        return super.update(sql, new Object[]{stuId,bookId, TimeTools.getTime(),TimeTools.getTime2()});
    }

    //更新图书馆藏量
    public int updateBook1(int num,int bookId) {
        String sql = "update tb_book set num=? where id=?";
        return super.update(sql, new Object[]{num, bookId});
    }

    //查询某个学生的借书记录
    public List<Book> getLendBookList(int studentId) {
        String sql = "SELECT b.*\n" +
                "FROM tb_lend l\n" +
                "LEFT JOIN tb_book b\n" +
                "ON l.book_id=b.id\n" +
                "WHERE l.student_id="+studentId;
        return super.selectAll(sql, new Object[]{});
    }

    //查询学生借书详情



    public int deleteLendRecord(int student_id, int book_id) {
        String sql = "delete from tb_lend where student_id=? and book_id=?";
        return super.update(sql, new Object[]{student_id, book_id});
    }

    @Override
    public Book rowMapper(ResultSet rs) throws SQLException {
        Book book = new Book();
        book.setId(rs.getInt("id"));
        book.setIsbn(rs.getString("isbn"));
        book.setBookName(rs.getString("book_name"));
        book.setAuthor(rs.getString("author"));
        book.setPublisher(rs.getString("publisher"));
        book.setNum(rs.getInt("num"));
        return book;
    }
}
